package com.itheima.reggie.web.controller;

import com.itheima.reggie.utils.QiNiuUtil;
import com.itheima.reggie.web.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传下载控制层
 *
 * @Name : CommonController
 * @Author : WuQiang
 * @Date : 2022-08-14 17:26
 * @Description : 文件上传下载控制层
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("文件上传失败");
        }

        //生成随机的图片文件名称
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        //调用七牛云工具类
        QiNiuUtil.upload(bytes, fileName);
        //将成功结果返回
        return R.success(fileName,fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        InputStream inputStream = QiNiuUtil.download(name);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
